//
//  SettingViewController.swift
//  jiaoyi
//
//  Created by wjk on 2018/8/16.
//  Copyright © 2018年 wjk. All rights reserved.
//

import UIKit
import Kingfisher

class SettingViewController: BaseViewController,UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!
    
    var datas = [[["name":"登录ID","isArrow":false],
                  ["name":"姓名","isArrow":false],
                  ["name":"电话","isArrow":false],
                  ["name":"手机","isArrow":true,"subTitle":(UIApplication.shared.delegate as! AppDelegate).user_name]],
                 [["name":"企业名称","isArrow":false],
                  ["name":"登记注册时间","isArrow":false]],
                 [["name":"清除缓存","isArrow":false],
                  ["name":"隐私政策","isArrow":true],
                  ["name":"关于我们","isArrow":true]]]
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = tableviewBackgroundColor()
        self.title = "账户设置"
        
        
        NetWorkRequest(.userinfoget()) { (res) -> (Void) in
            if res["code"] as!String == "000000" {
                let jd = jsonFormater(data: res["data"] as Any)
//                if jd["items"].dictionaryValue["enterprise_id"]?.isEmpty == false {
                
                    
                    var data2:[[String:Any]] = [[String:Any]]()
                    data2.append(["name":"企业名称","isArrow":false,"subTitle":jd["items"].dictionaryValue["enterprise"]?.dictionaryValue["name"]?.stringValue as Any])
                    data2.append(["name":"等级注册时间","isArrow":false,"subTitle":jd["items"].dictionaryValue["enterprise"]?.dictionaryValue["identity_a_attachment"]?.dictionaryValue["attachment"]?.dictionaryValue["created_at"]?.stringValue as Any])
                    
                    self.datas.replaceSubrange(Range(1..<2), with: [data2])
                    self.tableView.reloadData()
//                }
            }
        }
        
        
        NetWorkRequest(.daibiaoget()) { (res) -> (Void) in
            if res["code"] as! String == "000000" {
                let jd = jsonFormater(data: res["data"] as Any)
                if jd["name"].stringValue.isEmpty == false {
                    
                    
                    var data1:[[String:Any]] = [[String:Any]]()
                    data1.append(["name":"登录ID","isArrow":false,"subTitle":"\(jd["user_code"].stringValue) / \(jd["phone"].stringValue)"])
                    data1.append(["name":"姓名","isArrow":false,"subTitle":jd["name"].stringValue])
                    data1.append(["name":"电话","isArrow":false,"subTitle":jd["landline"].stringValue ])
                    data1.append(["name":"手机","isArrow":true,"subTitle":jd["phone"].stringValue])
                    
                    self.datas.replaceSubrange(Range(0..<1), with: [data1])
                    self.tableView.reloadData()
                }
            }
        }
        
        
        
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section>1 {
            return 10
        }
        return 40
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section < 2 {
            let label = UILabel(frame: CGRect(x: 0, y: 0, width: deviceWidth(), height: 40))
            label.font = UIFont.systemFont(ofSize: 16)
            label.textColor = baseColor()
            label.backgroundColor = tableviewBackgroundColor()
            label.text = (section==0) ? "     个人信息":"     企业信息"
            
            return label
        }
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: deviceWidth(), height: 10))
        label.backgroundColor = tableviewBackgroundColor()
        return label
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return datas.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return datas[section].count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
        let data = datas[indexPath.section][indexPath.row]
        cell?.selectionStyle = .none
        
        cell?.textLabel?.text = data["name"] as? String
        
        if data["name"] as? String == "清除缓存" {
            
            KingfisherManager.shared.cache.calculateDiskCacheSize { (size) in
                if size/1024 > 1023 {
                    cell?.detailTextLabel?.text = "\(size/1024/1024) MB"
                }else {
                    cell?.detailTextLabel?.text = "\(size/1024) KB"
                }
            }
            
        }else {
            cell?.detailTextLabel?.text = data["subTitle"] as? String
        }
        if data["isArrow"] as! Bool == true {
            cell?.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
        }else {
            cell?.accessoryType = UITableViewCellAccessoryType.none
        }
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let data = datas[indexPath.section][indexPath.row]
        if data["name"] as? String == "隐私政策" {
            self.navigationController?.pushViewController(WebViewController.showWebView(["http://2"], "隐私政策"), animated: true)
        }else if data["name"] as? String == "关于我们" {
            self.navigationController?.pushViewController(WebViewController.showWebView(["http://2"], "关于我们"), animated: true)
        }else if data["name"] as? String == "清除缓存" {
            let cache = KingfisherManager.shared.cache
            cache.clearDiskCache()//清除硬盘缓存
            cache.clearMemoryCache()//清理网络缓存
            cache.cleanExpiredDiskCache()//清理过期的，或者超过硬盘限制大小的
            self.tableView.reloadData()
            showMessage(message: "清理缓存成功")
        } else if data["name"] as? String == "手机" {
            self.navigationController?.pushViewController(R.storyboard.user.updateMobileViewController()!, animated: true)
        }
    }
    
    @IBAction func logout(_ sender: UIButton) {
        
        NetWorkRequest(.logout()) { (res) -> (Void) in
            UserDefaults.User.set("", forKey: .authorization)
            UserDefaults.User.set(false, forKey: .isLogin)
            self.navigationController?.popViewController(animated: false)
            self.tabBarController?.selectedIndex = 0
//            (self.tabBarController?.selectedViewController as! UINavigationController).pushViewController(R., animated: <#T##Bool#>)
        }
        
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
